package com.kingmed.kmss.framework.feign.client.kmcs;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kingmed.kmss.common.dto.kmcs.*;
import com.kingmed.kmss.common.dto.kmcs.resp.KMCSResp;
import com.kingmed.kmss.common.exception.external.ExternalApiException;
import com.kingmed.kmss.common.vo.CommonPage;
import feign.Response;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component
public class MsFeignServiceFacade {

    // Kmcs套餐接口每页查询多少个
    private static final int QUERY_PAGE_SIZE = 10000;

    @Autowired
    private MsFeignService remoteFeignService;
    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 物价级别、物价版本信息
     */
    public List<KmcsPriceDTO> handKmcsPrice(KmcsPriceQueryDTO queryDTO) {
        List<KmcsPriceDTO> result = new ArrayList<>();
        String areaName = queryDTO.getAreaName();
        try {
            queryDTO.setAreaName(StrUtil.EMPTY);
            Response response = remoteFeignService.itemPrice(queryDTO);
            if (response != null && response.status() == HttpStatus.HTTP_OK) {
                JSONObject jsonObject = JSONUtil.parseObj(IOUtils.toString(response.body().asInputStream(), StandardCharsets.UTF_8.toString()));
                JSONArray jsonArray = jsonObject.getJSONArray("result");
                this.handlePriceGrade(jsonArray, result);
            }
            if (StrUtil.isNotBlank(areaName) && CollectionUtils.isNotEmpty(result)) {
                return result.stream().filter(dto -> dto.getAreaName().contains(areaName)).collect(Collectors.toList());
            }
            return result;
        } catch (Exception e) {
            throw new ExternalApiException("查询Kmcs物价级别物价版本信息异常", e);
        }
    }

    private void handlePriceGrade(JSONArray jsonArray, List<KmcsPriceDTO> result) {
        if (jsonArray != null) {
            jsonArray.forEach(item -> {
                KmcsPriceDTO kmcsDto = JSONUtil.toBean(JSONUtil.toJsonStr(item), KmcsPriceDTO.class);
                if (kmcsDto != null) {
                    List<KmcsPriceDTO> list = new ArrayList<>();
                    this.handlePriceVersion(list, kmcsDto.getPriceVersionList());
                    kmcsDto.setPriceVersions(list);
                    kmcsDto.setPriceVersionList(StrUtil.EMPTY);
                    result.add(kmcsDto);
                }
            });
        }
    }

    private void handlePriceVersion(List<KmcsPriceDTO> prodDTOList, String jsonStr) {
        if (StrUtil.isNotBlank(jsonStr)) {
            JSONArray prodAry = JSONUtil.parseArray(JSONUtil.toJsonStr(jsonStr));
            prodAry.forEach(prod -> {
                KmcsPriceDTO kmcsDto = JSONUtil.toBean(JSONUtil.toJsonStr(prod), KmcsPriceDTO.class);
                if (kmcsDto != null) {
                    kmcsDto.setPriceVersionList(StrUtil.EMPTY);
                    prodDTOList.add(kmcsDto);
                }
            });
        }
    }

    /**
     * 套餐列表信息（分页）
     */
    public CommonPage<KmcsMpDTO> kmcsMpPage(KmcsMpQueryDTO queryDTO) {
        CommonPage<KmcsMpDTO> pageDto = new CommonPage<>();
        List<KmcsMpDTO> result = new ArrayList<>();
        try {
            Response response = remoteFeignService.kmcsMp(queryDTO);
            if (response != null && response.status() == HttpStatus.HTTP_OK) {
                JSONObject jsonObject = JSONUtil.parseObj(IOUtils.toString(response.body().asInputStream(), StandardCharsets.UTF_8.toString()));
                JSONObject resultObj = jsonObject.getJSONObject("result");
                if (resultObj != null) {
                    String total = resultObj.getStr("totalElements");
                    pageDto.setTotal(total != null ? Long.parseLong(total) : 0L);

                    pageDto.setPageNo(queryDTO.getNumber());
                    pageDto.setPageSize(queryDTO.getSize());

                    String totalPage = resultObj.getStr("totalPages");
                    pageDto.setTotalPage(totalPage != null ? Integer.parseInt(totalPage) : 0);
                    this.handleMp(resultObj, result);
                }
            }
            pageDto.setList(result);
            return pageDto;
        } catch (Exception e) {
            throw new ExternalApiException("查询Kmcs套餐列表信息异常", e);
        }
    }

    /**
     * 子公司所有套餐列表信息
     */
    public List<KmcsMpDTO> handBranchAllKmcsMp(KmcsMpQueryDTO queryDTO) {
        List<KmcsMpDTO> result = new ArrayList<>();

        int totalSize = 0;
        int pageNum = 1;
        int endPageNum;
        // 分页查询
        do {
            try {
                queryDTO.setNumber(pageNum);
                queryDTO.setSize(QUERY_PAGE_SIZE);
                Response response = remoteFeignService.kmcsMp(queryDTO);
                if (response != null && response.status() == HttpStatus.HTTP_OK) {
                    JSONObject jsonObject = JSONUtil.parseObj(IOUtils.toString(response.body().asInputStream(), StandardCharsets.UTF_8.toString()));
                    JSONObject resultObj = jsonObject.getJSONObject("result");
                    if (resultObj != null) {
                        totalSize = resultObj.getInt("totalElements");
                        this.handleMp(resultObj, result);
                    }
                }
                endPageNum = QUERY_PAGE_SIZE * pageNum;
                pageNum++;
            } catch (Exception e) {
                throw new ExternalApiException("查询Kmcs套餐列表信息异常", e);
            }
        } while (totalSize > endPageNum);

        return result;
    }

    /**
     * 套餐列表信息（不分页前n条数据）
     */
    public List<KmcsMpDTO> handKmcsMp(KmcsMpQueryDTO queryDTO) {
        List<KmcsMpDTO> result = new ArrayList<>();
        try {
            log.info("queryDTO === {}",JSONUtil.toJsonStr(queryDTO));
            Response response = remoteFeignService.kmcsMp(queryDTO);
            if (response != null && response.status() == HttpStatus.HTTP_OK) {
                JSONObject jsonObject = JSONUtil.parseObj(IOUtils.toString(response.body().asInputStream(), StandardCharsets.UTF_8.toString()));
                JSONObject resultObj = jsonObject.getJSONObject("result");
                if (resultObj != null) {
                    this.handleMp(resultObj, result);
                }
            }else{
                log.error("查询Kmcs套餐列表信息异常: {}", response);
            }
            return result;
        } catch (Exception e) {
            throw new ExternalApiException("查询Kmcs套餐列表信息异常", e);
        }
    }

    /**
     * 套餐列表信息（不分页全量数据）
     */
    public List<KmcsMpDTO> handKmcsMpList(KmcsMpQueryDTO queryDTO) {
        List<KmcsMpDTO> result = new ArrayList<>();
        try {
            Response response = remoteFeignService.kmcsMpList(queryDTO);
            if (response != null && response.status() == HttpStatus.HTTP_OK) {
                //JSONObject jsonObject = JSONUtil.parseObj(IOUtils.toString(response.body().asInputStream(), StandardCharsets.UTF_8.toString()));
                //JSONObject resultObj = jsonObject.getJSONObject("result");
                //if (resultObj != null) {
                //    this.handleMp(resultObj, result);
                //}
                KMCSResp<KmcsMpDTO> kmcsResp = objectMapper.readValue(response.body().asInputStream(), new TypeReference<KMCSResp<KmcsMpDTO>>() {});
                return kmcsResp.getResult().getContent();
            } else {
                log.error("调用kmcs接口异常：{}", response);
            }
            return result;
        } catch (Exception e) {
            throw new ExternalApiException("查询Kmcs全量套餐列表信息异常", e);
        }
    }

    // 套餐信息
    private void handleMp(JSONObject resultObj, List<KmcsMpDTO> result) {
        JSONArray jsonArray = resultObj.getJSONArray("content");
        if (jsonArray != null) {
            jsonArray.forEach(item -> {
                KmcsMpDTO mpDTO = JSONUtil.toBean(JSONUtil.toJsonStr(item), KmcsMpDTO.class);
                if (mpDTO != null) {
                    mpDTO.setTestItemList(StrUtil.EMPTY);
                    result.add(mpDTO);
                }
            });
        }
    }

    /**
     * 套餐(项目)列表信息
     */
    public List<KmcsMpProdDTO> kmcsMpProd(KmcsMpProdQueryDTO queryDTO) {
        List<KmcsMpProdDTO> result = new ArrayList<>();
        try {
            Response response = remoteFeignService.kmcsMpProd(queryDTO);
            if (response != null && response.status() == HttpStatus.HTTP_OK) {
                JSONObject jsonObject = JSONUtil.parseObj(IOUtils.toString(response.body().asInputStream(), StandardCharsets.UTF_8.toString()));
                JSONArray jsonArray = jsonObject.getJSONArray("result");
                if (jsonArray != null) {
                    jsonArray.forEach(item -> {
                        KmcsMpProdDTO mpDTO = JSONUtil.toBean(JSONUtil.toJsonStr(item), KmcsMpProdDTO.class);
                        if (mpDTO != null) {
                            mpDTO.setSubTestItemList(StrUtil.EMPTY);
                            result.add(mpDTO);
                        }
                    });
                }
            }
            return result;
        } catch (Exception e) {
            throw new ExternalApiException("查询Kmcs套餐(项目)列表信息异常", e);
        }
    }

    /**
     * 医院收费、省三级收费标准
     */
    public List<KmcsFeeDTO> handKmcsFee(KmcsFeeQueryDTO queryDTO) {
        List<KmcsFeeDTO> feeDTOList = new ArrayList<>();
        try {
            Response response = remoteFeignService.chargingStandard(queryDTO);
            if (response != null && response.status() == HttpStatus.HTTP_OK) {
                JSONObject jsonObject = JSONUtil.parseObj(IOUtils.toString(response.body().asInputStream(), StandardCharsets.UTF_8.toString()));
                JSONArray jsonArray = jsonObject.getJSONArray("result");
                if (jsonArray != null) {
                    jsonArray.forEach(obj -> {
                        KmcsFeeDTO feeDTO = JSONUtil.toBean(JSONUtil.toJsonStr(obj), KmcsFeeDTO.class);
                        if (feeDTO != null) {
                            feeDTO.setPriceGradeId(queryDTO.getPriceGradeId());
                            feeDTO.setPriceVersionId(queryDTO.getPriceVersionId());
                            feeDTOList.add(feeDTO);
                        }
                    });
                }
            }
            return feeDTOList;
        } catch (Exception e) {
            throw new ExternalApiException("查询Kmcs医院收费省三级收费标准异常", e);
        }
    }

    /**
     * 根据 mpId 查询医院收费、省三级收费标准
     * @param queryDTO
     * @return
     */
    public List<KmcsFeeDTO> handKmcsFeeByMpId(KmcsFeeQueryDTO queryDTO){
        List<KmcsFeeDTO> feeDTOList = new ArrayList<>();
        try{
            Response response = remoteFeignService.getMpInfoProvincePriceByMpId(queryDTO);
            if (response != null && response.status() == HttpStatus.HTTP_OK) {
                JSONObject jsonObject = JSONUtil.parseObj(IOUtils.toString(response.body().asInputStream(), StandardCharsets.UTF_8.toString()));
                JSONArray jsonArray = jsonObject.getJSONArray("result");
                if (jsonArray != null) {
                    jsonArray.forEach(obj -> {
                        KmcsFeeDTO feeDTO = JSONUtil.toBean(JSONUtil.toJsonStr(obj), KmcsFeeDTO.class);
                        if (feeDTO != null) {
                            feeDTO.setPriceGradeId(queryDTO.getPriceGradeId());
                            feeDTO.setPriceVersionId(queryDTO.getPriceVersionId());
                            feeDTOList.add(feeDTO);
                        }
                    });
                }
            }
            return feeDTOList;
        }catch (Exception e){
            throw new ExternalApiException("查询Kmcs医院收费省三级收费标准异常", e);
        }
    }

}
